package com.zyh.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@RestController
public class SedKillController {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @GetMapping("/sedKill/{id}")
    public String sedKill(@PathVariable("id") int id){
        long result = 0;
        try {
            //调用lua脚本并执行。
            DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
            redisScript.setResultType(Long.class);//返回类型是Long
            //lua文件存放在resources目录下
            redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("test.lua")));
            result = redisTemplate.execute(redisScript, Arrays.asList(id+""));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(result>0){
            System.out.println("购买成功，还剩"+result+"个");
            return "购买成功，还剩"+result+"个";
        }
        System.out.println("购买失败");
        return "购买失败";
    }
}
